<script setup lang="jsx">
import api from "./api";
import { $auth } from "@/utils";
import { to } from "@/utils/action";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
  url: { type: String, default: "" }, // 不传url默认使用导出中心导出
  name: { type: String, default: "" }, // 标签名称
  exportName: { type: String, default: "" }, // 导出名称
  mainKey: { type: String, default: "" }, // 列表主键，用于导出指定行
  tableRef: { type: Object, default: () => ({}) }, // 列表表格对象
  auth: { type: String, default: "" }, // 权限路径
});

const { url, mainKey } = props;
const load = ref(false);
const visible = ref(false);
let loadings = reactive({});
const form = ref({});
const fields = ref([]);
const exportConfig = ref({});

const emit = defineEmits(["close", "success"]);

const query = async (del) => {
  const res = await api.getConfig({ home_system: 2, tag_name: props.name });
  exportConfig.value = res.data;
  const { export_field } = res.data;
  if (!del) {
    fields.value = export_field;
    form.value.name = "";
  }
};

// 打开弹窗
const open = async () => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  await query();
  loadings = reactive({});
  checkIndex.value = null;
  visible.value = true;
};
// 关闭弹窗
const close = () => {
  visible.value = false;
};

const handleClose = () => {
  emit("close");
};

const handle = () => {
  if (!url) {
    open();
    return;
  }
  loadings.handle = true;
  const condition = {
    [mainKey + "s"]: props.tableRef.$table.getCheckboxRecords().map((d) => d[mainKey]),
    ...props.tableRef.getQueryForm(),
  };
  api
    .export(url, condition)
    .then((blob) => {
      ElMessage.success("导出成功，开始下载");
      props.tableRef.$table.saveFile({
        filename: props.exportName || props.name,
        type: "xlsx",
        content: blob,
      });
    })
    .finally(() => {
      loadings.handle = false;
    });
};

const prevRow = (index) => {
  const row = fields.value.splice(index, 1)[0];
  fields.value.splice(index - 1, 0, row);
  fields.value = [...fields.value];
};

const nextRow = (index) => {
  const row = fields.value.splice(index, 1)[0];
  fields.value.splice(index + 1, 0, row);
  fields.value = [...fields.value];
};

const table = ref();
const expt = (row, rowIndex = "") => {
  const { tpl_id, name: tpl_name } = row || {};
  const selection = table?.value.getCheckboxRecords();
  console.log(selection);
  if (!selection.length && !tpl_id) {
    ElMessage.error("请先选择字段");
    return;
  }
  loadings["expt" + rowIndex] = true;
  const condition = {
    [mainKey + "s"]: props.tableRef.$table.getCheckboxRecords().map((d) => d[mainKey]),
    ...props.tableRef.getQueryForm(),
  };
  api
    .taskExport({
      module: "goods",
      title: props.exportName || tpl_name || exportConfig.value.config_name,
      config_id: exportConfig.value.config_id,
      tpl_id,
      condition,
      fields: selection.map((d) => d.field_key),
    })
    .then((res) => {
      ElMessage.success("导出成功");
    })
    .finally(() => {
      loadings["expt" + rowIndex] = false;
    });
};

// 查看
const view = async (row) => {
  const names = fields.value
    .filter((d) => row.fields.includes(d.field_key))
    .map((d) => d.field_name);
  await 1;
  ElMessageBox({
    title: row.name,
    showCancelButton: true,
    showConfirmButton: false,
    cancelButtonText: "关闭",
    message: () => (
      <div
        class="flex flex-col gap-2"
        style="max-height: calc(100vh - 160px);overflow-x: hidden;overflow-y: auto"
      >
        {names.map((d) => (
          <div>{d}</div>
        ))}
      </div>
    ),
  }).catch(() => {});
};

// 添加模板
const addTamplate = () => {
  if (!form.value.name) {
    ElMessage.error("模板名称不能为空");
    return;
  }
  const selection = table?.value.getCheckboxRecords();
  if (!selection.length) {
    ElMessage.error("请先选择字段");
    return;
  }
  loadings.add = true;
  api
    .addTamplate({
      name: form.value.name,
      config_id: exportConfig.value.config_id,
      fields: selection.map((d) => d.field_key),
    })
    .then((res) => {
      form.value.name = "";
      query(true);
      ElMessage.success("保存成功");
    })
    .finally(() => {
      loadings.add = false;
    });
};

// 删除模板
const delelteTamplate = (row, rowIndex) => {
  ElMessageBox.confirm("是否确认删除模板？", "提示", {
    confirmButtonClass: "messagebox-confirm-button",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      loadings["delete" + rowIndex] = true;
      api
        .deleteTamplate(row.tpl_id)
        .then((res) => {
          query(true);
          ElMessage.success("删除成功");
        })
        .finally(() => {
          loadings["delete" + rowIndex] = false;
        });
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消操作" });
    });
};

// 选择模板
const checkIndex = ref(null);
const check = async (row, rowIndex) => {
  checkIndex.value = rowIndex;
  // 排序
  const { checkFields, noCheckFields } = fields.value.reduce(
    (acc, cur) => {
      if (row.fields.includes(cur.field_key)) {
        acc.checkFields.push(cur);
      } else {
        acc.noCheckFields.push(cur);
      }
      return acc;
    },
    { checkFields: [], noCheckFields: [] }
  );
  fields.value = row.fields
    .map((d) => checkFields.find((c) => d === c.field_key))
    .concat(noCheckFields);
  // 选中
  await table?.value.clearCheckboxRow();
  const rows = fields.value.filter((d) => row.fields.includes(d.field_key));
  table?.value.setCheckboxRow(rows, true);
};

// 保存模板
const edit = (row, rowIndex) => {
  const selection = table?.value.getCheckboxRecords();
  if (!selection.length) {
    ElMessage.error("请先选择字段");
    return;
  }
  loadings["edit" + rowIndex] = true;
  api
    .editTamplate(row.tpl_id, {
      name: row.name,
      condition: [],
      fields: selection.map((d) => d.field_key),
    })
    .then((res) => {
      console.log("res", res);
      query(true);
      ElMessage.success("保存模板成功");
    })
    .finally(() => {
      loadings["edit" + rowIndex] = false;
    });
};

const columns = ref([
  { type: "checkbox", width: 40 },
  { type: "seq", title: "序号", width: 60 },
  { field: "field_name", title: "字段", minWidth: 160 },
  {
    title: "排序",
    width: 140,
    slots: {
      default: ({ rowIndex }) => (
        <div>
          <el-button link type="primary" onClick={() => prevRow(rowIndex)}>
            上移
          </el-button>
          <el-button link type="primary" onClick={() => nextRow(rowIndex)}>
            下移
          </el-button>
        </div>
      ),
    },
  },
]);
const templateColumns = ref([
  {
    title: "名称",
    slots: {
      default: ({ row, rowIndex }) => (
        <div>
          <VText
            value={row.name}
            type="button"
            onClick={() => check(row, rowIndex)}
          ></VText>
        </div>
      ),
    },
  },
  {
    title: "操作",
    width: 220,
    slots: {
      default: ({ row, rowIndex }) => (
        <div>
          {checkIndex.value === rowIndex ? (
            <el-button
              link
              type="primary"
              loading={loadings["edit" + rowIndex]}
              onClick={() => edit(row, rowIndex)}
            >
              保存
            </el-button>
          ) : (
            ""
          )}
          <el-button link type="primary" onClick={() => view(row, rowIndex)}>
            查看
          </el-button>
          <el-button
            link
            type="primary"
            loading={loadings["expt" + rowIndex]}
            onClick={() => expt(row, rowIndex)}
          >
            导出
          </el-button>
          <el-button
            link
            type="danger"
            loading={loadings["delete" + rowIndex]}
            onClick={() => delelteTamplate(row, rowIndex)}
          >
            删除
          </el-button>
        </div>
      ),
    },
  },
]);

defineExpose({ open });
</script>

<template>
  <template v-if="$auth(auth)">
    <el-button :loading="loadings.handle" icon="Upload" v-bind="$attrs" @click="handle">
      <slot>导出</slot>
    </el-button>
    <el-dialog
      v-if="load"
      :close-on-click-modal="false"
      title="导出中心"
      v-model="visible"
      class="full v-export"
      append-to-body
      width="1000px"
      @close="handleClose"
    >
      <template #header>
        <span class="el-dialog__title">导出中心11</span>
        <span v-if="exportConfig.config_name"> - {{ exportConfig.config_name }}</span>
      </template>
      <div class="v-export-title">字段列表</div>
      <div class="v-export-wrapper">
        <vxe-grid ref="table" :columns="columns" :data="fields" height="auto" />
        <vxe-grid
          :columns="templateColumns"
          :data="exportConfig.templates"
          height="auto"
          class="v-export-table"
          :row-class-name="({ rowIndex }) => (checkIndex === rowIndex ? 'row-bg' : '')"
        />
        <div class="v-export-handle">
          <div class="v-export-handle-top">
            <el-button
              icon="upload"
              type="primary"
              :loading="loadings.expt"
              @click="expt()"
              >导出</el-button
            >
            <div class="v-export-handle-user">
              <el-icon size="16">
                <Warning />
              </el-icon>
              <div style="white-space: nowrap">
                导出结果在
                <el-link
                  type="primary"
                  @click="(visible = false) || to({ path: '/user/profile' })"
                  >个人中心</el-link
                >
                查看
              </div>
            </div>
          </div>
          <VGroup class="my-2">
            <el-input v-model="form.name" placeholder="请输入" class="w-full" />
            <el-button type="primary" :loading="loadings.add" plain @click="addTamplate"
              >保存模板</el-button
            >
          </VGroup>
        </div>
      </div>
      <template #footer>
        <el-button @click="close">关 闭</el-button>
      </template>
    </el-dialog>
  </template>
</template>

<style lang="scss" scoped>
.v-export {
  &-title {
    margin-top: 4px;
    margin-bottom: 8px;
  }
  &-wrapper {
    height: calc(100% - 40px);
    position: relative;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    column-gap: 12px;
  }
  &-table {
    padding-top: 80px;
  }
  &-handle {
    position: absolute;
    right: 0;
    top: 0;
    left: 50%;
    padding-left: 5px;
    &-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 4px;
    }
    &-user {
      display: flex;
      align-items: center;
      flex-wrap: nowrap;
    }
  }
  .row-bg {
    background-color: var(--el-color-primary-light-9);
  }
}
</style>
